[Home] Python으로 돌아가기

Comparison of C, Fortran, MATLAB, PYTHON, etc.

목차

1. 설명문(주석, Comments) 및 줄변경(Lines) 2. 산술 연산자 (Arithmetic Operators) 3. 관계 연산자 (Relational Operators) 4. 논리 연산자 (Logical Operators) 5. 콜론 연산자 (Colon Operators)

6. 데이터 타입 (Data Types) 7. 반복문 (Repeat statements) 8. 조건문 (Conditional statements) 9. 배열 (Array) 10. 행렬 연산 (Matrix Operation)

11. 부프로그램 (Sub-programs) 12. 전역 변수 (Global variables)

1. 설명문(주석, Comments) 및 줄변경(Lines)

언어 구문 줄바꿈 기호 줄연속 기호
C /* C 주석 (여러 줄) */ ; \ (백슬래시)
C++ // C++ 주석
/* C++ 주석 (여러 줄) */
; \ (백슬래시)
CSS /* CSS 주석 (여러 줄) */ ; 없음 (자동 연속)
F90 ! 포트란 주석 줄바꿈 자체 & (and 기호)
F77 * 포트란 주석 줄바꿈 자체 6열에 + (플러스)
HTML <!-- HTML 주석 (여러 줄) --> 태그 닫힘 없음
JS // JS 주석
/* JS 주석 (여러 줄) */
; \ (백슬래시)
JSP <%-- JSP 주석 (여러 줄) --%> ; 없음
MATLAB % MATLAB 주석 줄바꿈 자체 ... (마침표 3개)
PYTHON # 파이썬 주석
""" 여러 줄 주석 """
줄바꿈 자체 \ (백슬래시)

2. 산술 연산자 (Arithmetic Operators)

기능 MATLAB(1) PYTHON C++ F77
F90/95(2)
덧셈++++
뺄셈----
곱셈* 및 .****
나눗셈/ 및 .////
지수^ 및 .^**pow(3)**
나머지%%
증가분i+=1i++
감소분i-=1i--
그룹 구분( )( )( )( )

(1) MATLAB에서 연산자 앞의 ‘.’는 요소별(또는 스칼라) 연산이 필요할 경우 사용한다.

(2) F90/95에서는 필요한 경우 새로운 연산자를 정의하여 사용할 수 있다.

(3) xy는 함수를 사용하여, pow(x, y)로 나타낸다.

3. 관계 연산자 (Relational Operators)

기능 MATLAB PYTHON C++ F90/95 F77
Equal to========.EQ.
Not equal to~=!=!=/=.NE.
Less than<<<<.LT.
Less than or equal to<=<=<=<=.LE.
Greater than>>>>.GT.
Greater than or equal to>=>=>=>=.GE.
Object identityis
Negated object identityis not

4. 논리 연산자 (Logical Operators)

기능 MATLAB PYTHON C++ F90/95 F77
Logical NOT~not!.NOT..NOT.
Logical AND&&and&&.AND..AND.
Logical inclusive OR||or||.OR..OR.
Logical exclusive ORxor^.XOR..XOR.
Logical equivalent====.EQV..EQV.
Logical not equivalent~=!=.NEQV..NEQV.

(1) Bit logical AND, exclusive OR, OR, NOT에 대해서 &, ^, |, ~를 사용한다.

5. 콜론 연산자 (Colon Operators)

구문 F90/95 MATLAB/PYTHON 용법 F90/95 MATLAB/PYTHON
기본 형식B:E:I(1)B:I:E1. 배열 요소 위치사용가능사용가능
≥BB:B:2. 문자열에서 문자위치사용가능사용가능
≤E:E:E3. 반복문 제어사용불가사용가능
전체 영역:: 또는 ...(생략 기호)(2)4. 배열 요소 생성사용불가사용가능
마지막 인덱스-1(3)

(1) B = 시작값(beginning), E = 끝값(ending), I = 증분값(increment)

(2) 생략 기호(ELLIPSIS): 배열의 모두를 나타낼 때 Python에서는 '...'를 사용할 수 있다.


# 예) 
c = array([[1, 2, 3], [4, 5, 6]])
>>> c[...]
Out[13]: array([[1, 2, 3], [4, 5, 6]])

>>> c[-1,:]
Out[14]: array([4, 5, 6])

>>> c[:,-1]
Out[15]: array([3, 6])
        

(3) 배열의 마지막 인덱스: Python에서는 '-1'를 사용할 수 있다.

6. 데이터 타입 (Data Types)

변수(저장) MATLAB PYTHON C++ F90/95 F77
byte실수/복소수(1)정수/실수/복소수charcharacter::character
정수문자문자열: "", 리스트: [], 튜플: ()intinteger::integer
실수dictionary: {:, ...}floatreal::real
배정도 실수set: {}doublereal*8::double precision
복소수Boolean: True, Falsecomplex::complex
논리자(Boolean)Binary: bytes, bytearray, memoryviewboollogical::logical
Parameterparameter::parameter
포인터*pointer::
구조문structtype::

(1) C++에는 복소수형 변수에 대한 특별한 내장형 변수형태가 없다.

7. 반복문 (Repeat statements)

기능 MATLAB PYTHON C++ F90/95 F77
유한 반복문for k=1:nfor i in range(n):for k=1:n { }do k=1,ndo # k=1,n
무한 반복문whilewhile True:while { }do while-
반복문 종료 및 탈출breakbreakbreakexitgo to
반복문 1회 건너뜀-continuecontinuecyclego to
메시지 출력 후 멈춤errorexcepterror()stopstop
호출함수로 환원returnreturnreturnreturnreturn
조건부 반복문initialize test while_Lexpress true group change test endinitialize test while True: key = input() print(key)initialize test while (Lexpress) { true group change test }initialize test do while (Lexpress) true group change test end doinitialize test # continue if (Lexpress) then true group change test go to # end if
기능 MATLAB PYTHON C++ F90/95
색인 반복문for index=matrix statements endfor i in range(10): statements xdata = [0.1,4,3] for x in xdata:for (init;test;inc) { statements }do index=b,e,i statements end do
Pretest 반복문while (test) statements endwhile (test) statementswhile (test) { statements }do while (test) statements end do
Posttest 반복문items = [9,5,4,10] for idx, val in enumerate(items):do { statements } while (test)do statements if (test) exit end do

8. 조건문 (Conditional statements)

기능 MATLAB PYTHON C++ F90/95 F77 JavaScript
조건부 실행 if
end
if a > 0: if { } if then
end if
if then
end if
if (a > 0) { }
조건부 교체 else else: else else else else { }
elseif elif: else if elseif then elseif then else if (b > 0) { }
조건부 선택 switch/case 문 없으므로, if 문 사용 switch { } select case
end select
if then
end if
switch (x) {
case 1: break;
case 2: break;
default: break;
}
기능 MATLAB PYTHON C++ F90/95
논리형 IF문if L_express
true group
end
if (L_express):
true group
if (L_express) {
true group
}
if (L_express) then
true group
end if
기능 MATLAB PYTHON C++ F90/95
내부 IF문if L_express1
true group A
if L_express2
true group B
end
true group C
end
statement group D
if L_express1:
true group A
if L_express2:
true group B
true group C
statement group D
if (L_express1) {
true group A
if (L_express2) {
true group B
}
true group C
}
statement group D
if (L_express1) then
true group A
if (L_express2) then
true group B
end if
true group C
end if
statement group D
기능 MATLAB PYTHON C++ F90/95
IF-ELSE문if L_express
true group A
else
true group B
end
if L_express:
true group A
else:
true group B
if (L_express) {
true group A
} else {
true group B
}
if (L_express) then
true group A
else
true group B
end if
기능 MATLAB PYTHON C++ F90/95
IF-ELSE-IF문if L_express1
true group A
elseif L_express2
true group B
else
default group C
end
if L_express1:
true group A
elif L_express2:
true group B
else:
default group C
if (L_express1) {
true group A
} else if (L_express2) {
true group B
} else {
default group C
}
if (L_express1) then
true group A
else if (L_express2) then
true group B
else
default group C
end if

9. 배열 (Array)

기능 MATLAB C++ F90/95 F77
조건부 배열 제어if-where-
조건부 배열 교체else-elsewhere-
elseif---
기능 MATLAB F90/95
배열이름 생성()()
성분들 구분,,
성분들 자동 생성::
구분;;
성분들 생성[](/ /)
줄간 연결...&
출력 금지;default

10. 행렬 연산 (Matrix Operation)

- 행렬 연산 비교

기능 수식 MATLAB F90/95 前 크기 後 크기
스칼라+스칼라c = a ± bc = a ± b;c = a ± b1×11×1
요소+스칼라cjk = ajk ± bc = a ± b;c = a ± bm×n, 1×1m×n
요소+요소cjk = ajk ± bjkc = a ± b;c = a ± bm×n, m×nm×n
스칼라×스칼라c = a * bc = a * b;c = a * b1×11×1
요소×스칼라cjk = ajk × bc = a * b;c = a * bm×n, 1×1m×n
요소×요소cjk = ajk × bjkc = a .* b;c = a * bm×n, m×nm×n
스칼라/스칼라c = a / bc = a / b;c = a / b1×11×1
요소/스칼라cjk = ajk / bc = a / b;c = a / bm×n, 1×1m×n
요소/요소cjk = ajk / bjkc = a ./ b;c = a / bm×n, m×nm×n
스칼라 멱승c = abc = a ^ b;c = a ** b1×11×1
요소 멱승cjk = ajkbc = a ^ b;c = a ** bm×n, 1×1m×n
요소 멱승cjk = ajkbjkc = a .^ b;c = a ** bm×n, m×nm×n
전체배열Ckj = AjkC = A';C = transpose(A);m×nn×m
배열×배열Cij = ∑kAikBkjC = A * B;C = matmul(A,B);m×r, r×nm×n
스칼라곱c = ∑kAkBkc = sum(A .* B);c = sum(A * B);m×1, 1×m1×1
스칼라곱c = A' * B';c = dot_product(A,B);m×1, 1×11×1

- 배열 및 행렬 연산 비교

기능 MATLAB PYTHON C++ F90/95
1차원 배열 초기화A(100)=0
for j=1:100
A(j)=12
end
또는
A=12*ones(1,100)
np.ones([3,3])
np.ones([3,3],dtype='int32')
np.zeros([3,3])
np.empty([3,3])
mx1 = np.array([[5,10], [15,20]])
int A[100];
for (j=0; j<100; j++)
A[j]=12;
integer A(100)
A=12
2차원 배열 초기화A=ones(10,10)int A[10][10]integer A(10,10)
배열 초기화 및 할당A=zeros(2,3)
A=[1,7,2;
3,4,6]
int A[2][3];
int A[2][3] = { {1,7,2}, {3,4,6} };
integer, dimension(2,3):: A
A(1,:) = (/1,7,2/)
A(2,:) = (/3,4,6/)

행렬 연산

기능 MATLAB PYTHON C++ F90/95
곱셈 (C=AB)C=A*BC1=np.dot(A,B)
C2=np.matmul(A,B)
C3=A@B
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
C[i][j]=0;
for (k=0; k<10; k++) {
C[i][j] += A[i][k] * B[k][j];
}}}
C=matmul(A,B)
스칼라곱C=a*BZ = X.copy() # deep copy
Y = X # shallow copy
for (i=0; i<10; i++) {
for (j=0; j<10; j++) {
C[i][j]=a*B[i][j];
}}
C=a*B
역행렬B=inv(A)import scipy.linalg as linalg
Ainv = linalg.inv(A)

11. 부프로그램 (Sub-programs)

기능 MATLAB PYTHON C++ F90/95
프로그램statements
[y1⋯yn]=f(a1,⋯,am)
[end of file]
statements
y1,⋯,yn = f(a1,⋯,am)
main(ac, char **av) {
statements
y = f(a1,⋯,am);
}
program main
type y
type a1,⋯,type am
statements
y=f(a1,⋯,am)
call s(a1,⋯,am)
end program
서브루틴void f (type a1,⋯,type am) {
statements
}
subroutine s (a1,⋯,am)
type a1,⋯,type am
statements
end
함수function [r1⋯m]
=f(a1,⋯,am)
statements
def computeProps(n,p,q):
a,b,c=n,p,q
return (a,b,c)
type f (type a1,⋯,type am) {
statements
}
function f(a1,⋯,am)
type f
type a1,⋯,type am
statements
end
단일 인수function out = name (in)name (in, out)function name (in)
function name (in) result (out)
다중 인수function [inout, out2] = name (in1,in2,inout)name (in1, in2, inout, out2)subroutine name (in1, in2, inout, out2)

12. 전역 변수 (Global variables)

기능 MATLAB PYTHON C++ F90/95 F77
전역변수 선언global variablesglobal variablesexternal variablesmodule name
save
type(t):: variables
end module name
common /name/ variables
전역변수 호출global variablesglobal variablesexternal variablesuse namecommon /name/ variables